package scalaExec.scalaLab;


import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import scalaExec.ClassLoaders.ExtensionClassLoader;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
import java.net.URI;
import java.net.URL;

import java.util.regex.*;
import scalaExec.gui.*;

import scalaExec.Interpreter.GlobalValues;

import java.net.URLDecoder;

import javax.help.CSH;
import javax.swing.event.*;
        
/**
 * Simple GUI for the scalaLab
 */
public class scalaLab extends JFrame implements WindowListener, ActionListener
        
{
        static private String netbeansScalaLabArg;  // name of ScalaLab executable .jar when starting from Netbeans
    // applications that can start from within
        static public scalaLab uiMainFrame; 
        public  JTabbedPane  tabbedToolbars;
        public  JTabbedPane  tabbedToolbarsUnDocked;
        
        
        public  JMenuBar  mainJMenuBar;
        
    	private JMenu   editMenu;
        private JMenuItem  fileExplorerFocusMenuItem;
        private JMenuItem jLabIDEJMenuItem;
        private JMenuItem editJMenuItem;
        private JMenuItem editDSPJMenuItem;
        private JMenuItem jeditJMenuItem;
        private JMenuItem jeditDSPJMenuItem;

        public JMenu    FileMenu;
        
        private JMenuItem saveVars;
        private JMenuItem loadVars;
        private JMenuItem saveHistoryItem;
        private JMenuItem loadHistoryItem;
        private JMenuItem displayHistoryItem;
        private JMenuItem clearHistoryItem;
        private JMenuItem appendVars;
        
        
        private JMenu     confMenu;
        private JMenuItem controlMainToolbarJMenuItem;
        private JMenuItem resetInterpreterJMenuItem;
        private JMenuItem adjustFontMenuItem;
        private JMenuItem adjustLookAndFeelMenuItem;
        private JMenuItem varsConfJMenuItem;
        private JMenuItem saveConfParamsJMenuItem;
        private JMenuItem browseFileSysForPathsJMenuItem;
        private JMenuItem browseClassesJMenuItem;
        private JMenuItem promptJMenuItem;
        private JMenuItem outputConsoleJMenuItem;
        private JMenuItem configAlphaParamJMenuItem;

        private JMenu swingConsoleMenu;
        private JMenuItem swingConsoleMenuItemJAMA;
        private JMenuItem swingConsoleMenuItemEJML;
        
        
        private JMenu ProjectMenu;
        private JMenuItem scalaSciParametersJItem;
        private JMenuItem CompileScriptsOnScalaLabClasspathJItem;
        private JMenuItem ConfigureScalaJItem;
        private JMenuItem NewProjectJItem;
        private JMenuItem OpenProjectJItem;
        private JMenuItem SaveProjectJMenuItem;
        private JMenuItem CloseProjectJMenuItem;

        
        private JMenu JavaMenu;
        private JMenu ScalaMenu;
        //private JMenu FastSciMenu;
        
        public JMenuItem  getPromptJMenuItem()  { return promptJMenuItem; }
        public JMenuItem  getConsoleOutputJMenuItem() { return outputConsoleJMenuItem; }
        
        private JMenuItem loadConfParamsJMenuItem;
        private JMenuItem trigonometricFunctionsJMenuItem;
        private JMenuItem toolboxesToolbarJMenuItem;
     
        private JMenu    examplesMenu;
        private JMenuItem ScalaExamplesHelpJMenuItem;
        private JMenuItem ScalaSciExamplesHelpJMenuItem;
        //private JMenuItem FastSciExamplesHelpJMenuItem;
        private JMenuItem ScalaExamplesPlotHelpJMenuItem;
        private JMenuItem ScalaExamplesODEHelpJMenuItem;
        private JMenuItem ScalaExamplesWEKAHelpJMenuItem;
        private JMenuItem ScalaExamplesWaveletHelpJMenuItem;
        private JMenuItem ScalaExamplesJOONEHelpJMenuItem;
        private JMenuItem ScalaExamplesBioJavaHelpJMenuItem;
        private JMenuItem ScalaExamplesLAHelpJMenuItem;
          
        private JMenu JavaHelpMenu;

        private JMenu scalaCellsMenu;
        private JMenuItem openScalaCellsJMenuItem;
        
        private JMenu     helpMenu;
        private JMenuItem basicHelpJMenuItem;
        private JMenuItem aboutHelpJMenuItem;
        private JMenuItem memoryHelpJMenuItem;
        private JMenu     searchMenu;
        private JMenuItem searchClassesJMenuItem;
        
        
        private JMenu  wizardsMenu;
        private JMenuItem wizardsScalaSciJMenuItem, wizardsScalaSciScalaJMenuItem;
        
        private JMenuItem autocompletionJMenuItem;
        private JMenuItem autocompletionRegExJMenuItem;
        private JMenuItem bufferedLineInputJMenuItem;
        private JMenuItem JavaSciHelpJMenuItem;
        private JMenuItem ScalaHelpJMenuItem;
        private JMenuItem GettingStartedJMenuItem;
        private JMenuItem ScalaLabArchitectureJMenuItem;
        private JMenuItem watchVariablesUpdateJMenuItem ;
        private JMenuItem exitJMenuItem; 
        
        private JMenuItem jScriptsMenuItem;
        
        static public  Dimension ScreenDim;
        
        static JScrollPane  varsScrolPane;
        static JScrollPane  historyScrolPane;
        static JScrollPane  pathsScrollPane;
        public static JSplitPane      outerPane;
        static public JTabbedPane     uiTabbedPane;
        
        /**The area used for user input and where the answers are displayed*/
        public scalaExec.gui.scalalabConsole   scalalabConsole;
        private JScrollPane  consPane;
        private JPanel consPanel; // the console's panel
        public static  JPanel  historyPanel = new JPanel();
        public  static JPanel    variablesWorkSpacePanel = new JPanel();
        public  static JScrollPane lastResultScrollPane = new JScrollPane(GlobalValues.lastResultOutputArea);
        
        public static scalaLabExplorer    explorerPanel;
        
        public JFrame myId;

        public  static int xSizeMainFrame, ySizeMainFrame;
        public  static int xLocMainFrame, yLocMainFrame;

         private  static URL watchURL;
         private String JavaHelpStr,   ScalaHelpStr;
         private URL  displayCachedClassesURL, ODEWizardURL;
         private URL  pathsConfigURL;
         private URL editURL, browseJFileURL, loadClassesFromJarsURL;
         private URL SQLURL, saveURL, userFunctionsURL;
         private Image watchImage, displayCachedClassesImage, sunJavaImage, ODEWizardImage;
         private Image editImage, scalalabPathsConfigImage, loadClassesFromJarsImage;
         private Image pathsConfigImage;
         private Image saveImage, userFunctionsImage;

         public  Image dukeImage, scalaImage,  scalaImageSmall, javaHelpImage,  IDEImage, thumbsImage;
         public Image dukeAnimImage;
         public Image configImage;
         
         static Class [] formals = { String [].class };
         static Object [] actuals = { new String [] {""}};

        static public JTable  varsTable;
        static public JPopupMenu variablesPanelPopupMenu;
        static public JPopupMenu historyPanelPopupMenu;
        
        public GlobalValues  instanceGlobals;

        private int   horizDividerLoc;
        private double horizDividerLocVarsLastOutput;
        private int  vertDividerLocConsole;

        // for history list handling
        private Object[] values;  // currently selected values
        private JList historyList;
        private String watchStr;

      	 
        /**Reacts to the user menu and update (if necessary) the interface.*/
        public void actionPerformed(ActionEvent e)
        {
                Object o = e.getSource();

                if (o == exitJMenuItem ) {
                        closeGUI();
                }
        }

        

        public static void initAutocompletion() {
        //System.out.println("GlobalValues.fullJarFilePath = "+GlobalValues.fullJarFilePath+"  GlobalValues.jarFilePath = "+GlobalValues.jarFilePath);
            scalaExec.Interpreter.GlobalValues.autoCompletionScalaSci = new scalaExec.gui.AutoCompletionScalaSci();

        scalaExec.Interpreter.GlobalValues.autoCompletionScalaSciLoader = new scalaExec.gui.AutoCompletionScalaSciLoader(GlobalValues.jarFilePath, GlobalValues.ScalaSciClassPath, null);

        scalaExec.Interpreter.GlobalValues.autoCompletionScalaSciLoader.loadClasses();
        }

        /**Function called when the gui is being close*/
        public void closeGUI()
        {
                File outPropFile = new File(GlobalValues.workingDir+File.separator+"scalalab.props");
    try {
   FileOutputStream outFile= new FileOutputStream(outPropFile);
   GlobalValues.passPropertiesFromWorkspaceToSettings(GlobalValues.settings);  // update properties to the current values kept in workspace
   GlobalValues.settings.store(outFile, "Saved scalaLab global conf parameters");
    outFile.close();
    scalaExec.scalaLab.commandHistory.saveCommandHistory(scalaExec.Interpreter.GlobalValues.scalalabCommandHistoryFile, GlobalValues.userConsole.previousCommands);
    scalaExec.scalaLab.favouritePaths.saveFavouritePaths(scalaExec.Interpreter.GlobalValues.scalalabFavoritePathsFile, scalaExec.Interpreter.GlobalValues.scalalabMainFrame.explorerPanel.favouritePathsCB);
    System.exit(0);
    }
    catch (Exception fnfe) {
        JOptionPane.showMessageDialog(null, "Cannot write configuration file. Perhaps you do not have access rights for write, try making a shortcut to scalalab using a proper \"Start in\" directory ","Cannot write configuration file", JOptionPane.INFORMATION_MESSAGE);
        System.out.println("error opening file for writing configuration");
        fnfe.printStackTrace();
        System.exit(0);
    }
  
  }


  /*
    * This method will take a file name and try to "decode" any URL encoded characters.  For example
    * if the file name contains any spaces this method call will take the resulting %20 encoded values
    * and convert them to spaces.
    *
    */
    public static String decodeFileName(String fileName) {
        String decodedFile = fileName;

        try {
            decodedFile = URLDecoder.decode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.err.println("Encounted an invalid encoding scheme when trying to use URLDecoder.decode().");
            System.err.println("Please note that if you encounter this error and you have spaces in your directory you will run into issues. ");
        }

        return decodedFile;
    }

        /**Create the main graphical interface (menu, buttons, delays...).*/
        public scalaLab( String ScalaSciClassPath, String [] additionalToolboxes)
        {
           
                setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                String crossPlatformLookAndFeel="";
                ScreenDim = Toolkit.getDefaultToolkit().getScreenSize();
                //position the frame in the centre of the screen
                xSizeMainFrame = (int)((double)ScreenDim.width/1.2);  
                ySizeMainFrame = (int)((double)ScreenDim.height/1.4);
                xLocMainFrame = (ScreenDim.width-xSizeMainFrame) / 25;
                yLocMainFrame = (ScreenDim.height-ySizeMainFrame)/25 ; 
               
                GlobalValues.sizeX = xSizeMainFrame;
                GlobalValues.sizeY = ySizeMainFrame;
                horizDividerLoc =  (int)(0.3*xSizeMainFrame);
                horizDividerLocVarsLastOutput =0.5;
                vertDividerLocConsole = (int)(0.2*ySizeMainFrame);
        
                GlobalValues.figFrameSizeX = (int)((double)xSizeMainFrame/1.5);
                GlobalValues.figFrameSizeY = (int)((double)ySizeMainFrame/1.5);
            
            initHelpObjects();
        
   //  html documentation URLs     
            JavaHelpStr = "http://java.sun.com/javase/6/docs/api/";
            ScalaHelpStr = "http://www.scala-lang.org/docu/files/api/index.html";
            // int startIdx = watchStr.indexOf("resources");
            
       
        // setup interface for interaction with the scalaLab's computation server
       URL networkImageURL = getClass().getResource("resources/network-idle.png");
       URL networkHasResultsImageURL  = getClass().getResource("resources/hint.png");
       URL networkWaitingForServerResults = getClass().getResource("resources/clock.png");
       
        URL javaHelpURL = getClass().getResource("resources/javaHelp.gif");
        URL thumbsURL =  getClass().getResource("resources/Thumbs.db");
        
        URL dukeAnimImageURL = getClass().getResource("resources/dukeMoving.gif");
        URL dukeImageURL = getClass().getResource("resources/duke.png");
        URL scalaImageURL = getClass().getResource("resources/scala.gif");
        URL scalaSmallImageURL = getClass().getResource("resources/smallScalaImage.jpg");
          
    //    URL configImageURL = getClass().getResource("resources/config.png");
        
   dukeImage = Toolkit.getDefaultToolkit().getImage(dukeImageURL);
   scalaImage = Toolkit.getDefaultToolkit().getImage(scalaImageURL);
   scalaImageSmall = Toolkit.getDefaultToolkit().getImage(scalaSmallImageURL);
   
   //configImage = Toolkit.getDefaultToolkit().getImage(configImageURL);
   javaHelpImage = Toolkit.getDefaultToolkit().getImage(javaHelpURL);
   thumbsImage = Toolkit.getDefaultToolkit().getImage(thumbsURL);
   dukeAnimImage = Toolkit.getDefaultToolkit().getImage(dukeAnimImageURL);
   
       
       //GlobalValues.scriptingModeConfigIcon = new ImageIcon(configImage);
       
            watchImage = Toolkit.getDefaultToolkit().getImage(watchURL);
            SQLURL = getClass().getResource("resources/question.gif");
            userFunctionsURL = getClass().getResource("resources/edu_mathematics.png");
            userFunctionsImage = Toolkit.getDefaultToolkit().getImage(userFunctionsURL);
            ODEWizardURL = getClass().getResource("resources/wizard.png");
            ODEWizardImage = Toolkit.getDefaultToolkit().getImage(ODEWizardURL);
            displayCachedClassesURL = getClass().getResource("resources/sun-java.png");
            displayCachedClassesImage = Toolkit.getDefaultToolkit().getImage(displayCachedClassesURL);
            sunJavaImage = Toolkit.getDefaultToolkit().getImage(displayCachedClassesURL);
            editURL = getClass().getResource("resources/jedit.png");
            editImage = Toolkit.getDefaultToolkit().getImage(editURL);
            saveURL = getClass().getResource("resources/save.gif");
            saveImage = Toolkit.getDefaultToolkit().getImage(saveURL);
            browseJFileURL = getClass().getResource("resources/system-search.png");
            pathsConfigURL = getClass().getResource("resources/paths.png");
            pathsConfigImage = Toolkit.getDefaultToolkit().getImage(pathsConfigURL);
            scalalabPathsConfigImage = Toolkit.getDefaultToolkit().getImage(pathsConfigURL);
            loadClassesFromJarsURL = getClass().getResource("resources/loading.png");
            loadClassesFromJarsImage = Toolkit.getDefaultToolkit().getImage(loadClassesFromJarsURL);
                     // Force SwingSet to come up in the Cross Platform L&F
	try
        {
            if (GlobalValues.hostIsUnix==false)  {
            String sysLookAndFeel = UIManager.getSystemLookAndFeelClassName();
            UIManager.setLookAndFeel(sysLookAndFeel);
            }
            else {
         crossPlatformLookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
         UIManager.setLookAndFeel(crossPlatformLookAndFeel);
         }
        }
            catch (Exception exc) {
             System.err.println("Error loading L&F: " + exc);
	}

        InitConsole();
        
        watchImage = Toolkit.getDefaultToolkit().getImage(watchURL);
        InitJMenuBar(this);
                 myId = this;
                 GlobalValues.scalalabMainFrame = this;   // keep instance of scalaLab main frame
                 GlobalValues.initGlobals();
                 
                             GlobalValues.consoleOutputWindow = new SysUtils.ConsoleWindow();
            System.setOut(GlobalValues.consoleOutputWindow.consoleStream);

            
        SwingUtilities.invokeLater(new Runnable() {
     public void run() {  // run in  */
                myId.setSize(xSizeMainFrame, ySizeMainFrame);
                myId.setLocation(xLocMainFrame, yLocMainFrame);
                myId.addWindowListener((WindowListener)myId);
                
                String  bufferedLineMode = ",  Line Input Mode, ";
                if (GlobalValues.commandLineModeOn == false)
                    bufferedLineMode = ",  Buffered Input Mode, ";
                
                
                ConsoleKeyHandler.updateModeStatusInfo();

                myId.setResizable(true);
        
        uiTabbedPane = new JTabbedPane();
        GlobalValues.scalaImage = scalaExec.Interpreter.GlobalValues.scalalabMainFrame.scalaImage; 
        GlobalValues.smallScalaImage = scalaExec.Interpreter.GlobalValues.scalalabMainFrame.scalaImageSmall;
        GlobalValues.scalalabMainFrame.setIconImage(GlobalValues.smallScalaImage);
                 
        
        uiTabbedPane.addTab("", new ImageIcon(GlobalValues.scalaImage), null);
        uiTabbedPane.setToolTipTextAt(GlobalValues.mainTab, "The main tab consists of the Console Prompt, the Explorer and the Workspace viewer"); 
        
        
        uiTabbedPane.addTab("Java Help",null, null);
        uiTabbedPane.addTab("Scala Help", null, null);
        uiTabbedPane.setToolTipTextAt(GlobalValues.javaHelpTab, "Link to the official Java APIs HTML documentation");
        
        
        uiTabbedPane.addTab("ScalaSci Toolboxes",  null, null);
        add(uiTabbedPane, "Center");
        
        scalaExec.gui.ConsoleKeyHandler.updateModeStatusInfo();  // update the information about scalaLab's console inputCons mode
        
     
           // refocus always on the main input console window
        uiTabbedPane.addFocusListener(new FocusListener() {
           public void focusGained(FocusEvent e) {
                        FocusEvent fe = new FocusEvent(scalalabConsole, FocusEvent.FOCUS_GAINED);
                        scalalabConsole.dispatchEvent(fe);    
         }
           public void focusLost(FocusEvent e) {
                        FocusEvent fe = new FocusEvent(scalalabConsole, FocusEvent.FOCUS_GAINED);
                        scalalabConsole.dispatchEvent(fe);    
                    }
                });
        
        uiTabbedPane.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
              int n = uiTabbedPane.getSelectedIndex();
              loadTab(n);
                    }
                });
      
                loadTab(GlobalValues.mainTab);

        scalaExec.scalaLab.commandHistory.loadCommandHistory(scalaExec.Interpreter.GlobalValues.scalalabCommandHistoryFile, GlobalValues.userConsole.previousCommands);
GlobalValues.passPropertiesFromSettingsToWorkspace(GlobalValues.settings);
        
     } 


  });
        }
        
         private  class MouseAdapterForHistory extends  MouseAdapter {

             public void mouseClicked(MouseEvent evt) {
                 if (evt.getClickCount() == 2) {
                 
               StringBuilder text = new StringBuilder();
               for (int i = 0; i < values.length; i++)
               {
                  String word = (String) values[i];
                  text.append(word);
                  text.append(" ");
               }

         GlobalValues.scalalabMainFrame.scalalabConsole.scalaInterpreter.interpret(text.toString());
                  }
             }

           public void mousePressed(MouseEvent e) {   
               
                 historyPanelPopupMenu  = new JPopupMenu(); 
                 JMenuItem clearHistoryLocalItem = new JMenuItem("Clear History");
                 clearHistoryLocalItem.addActionListener(new clearHistoryAction());
                JMenuItem loadHistoryLocalItem = new JMenuItem("Load History");
                 loadHistoryLocalItem.addActionListener(new loadHistoryAction());
                JMenuItem saveHistoryLocalItem = new JMenuItem("Save History");
                 saveHistoryLocalItem.addActionListener(new saveHistoryAction());
    
                 historyPanelPopupMenu.add(clearHistoryLocalItem);
                 historyPanelPopupMenu.add(loadHistoryLocalItem);
                 historyPanelPopupMenu.add(saveHistoryLocalItem);
                 
               if (e.isPopupTrigger()){  
               historyPanelPopupMenu.show((Component) e.getSource(), e.getX(), e.getY());
             }
           }
    
            public void mouseReleased(MouseEvent e) { 
           if (e.isPopupTrigger()){
                historyPanelPopupMenu.show((Component) e.getSource(), e.getX(), e.getY());
             }       
             
          }
       }
       
        public void updateHistoryWindow() {
             historyList = new JList(GlobalValues.userConsole.previousCommands);
             historyPanel.removeAll();
             historyPanel.add(historyList);
             historyList.setToolTipText("History of recent commands. You can reexecute a command by selecting it. Double-clicking the command executes it directly..");
             historyList.addMouseListener(new MouseAdapterForHistory());
         
             
             historyList.addListSelectionListener(new        ListSelectionListener()
         {
            public void valueChanged(ListSelectionEvent event)
            {  
               values = historyList.getSelectedValues();

               StringBuilder text = new StringBuilder();
               for (int i = 0; i < values.length; i++)
               {  
                  String word = (String) values[i];
                  text.append(word);
                  text.append(" ");
               }
               
               // replace current command with next command
    	String textArea = GlobalValues.userConsole.getText();
    	int    pos1     = textArea.lastIndexOf("# ") + 2;
    	GlobalValues.userConsole.setText(textArea.substring(0,pos1)+text);
    	
    	// set cursor at the end of the text area
        GlobalValues.userConsole.setCaretPosition(GlobalValues.userConsole.getText().length());

            }
         });



        } 
        
        private void loadTab(int n)
        {
            String  title = uiTabbedPane.getTitleAt(n);
            
            Dimension dimTab = uiTabbedPane.getSize();
            GlobalValues.xSizeTab = dimTab.width;
            GlobalValues.ySizeTab = dimTab.height;
                  
        
        switch (n)  {
                case GlobalValues.mainTab:
        
        
        variablesWorkSpacePanel = new JPanel(new BorderLayout());
        updateHistoryWindow();
        
        varsScrolPane = new JScrollPane(variablesWorkSpacePanel);
        historyScrolPane = new JScrollPane(historyPanel);
        
        lastResultScrollPane.setToolTipText("The result of the last command");
         
        JSplitPane varsLastOutSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, varsScrolPane, lastResultScrollPane);
        int divlocVarsLastOut = (int)(GlobalValues.scalalabMainFrame.getSize().width/4.0);
        varsLastOutSplitPane.setDividerLocation(divlocVarsLastOut);
       
      
        int divlocHistVars = (int)(GlobalValues.scalalabMainFrame.getSize().height/8.0);
        JSplitPane historyVarsPanel = new JSplitPane(JSplitPane.VERTICAL_SPLIT, historyScrolPane, varsLastOutSplitPane);
        historyVarsPanel.setDividerLocation(divlocHistVars);
        
        explorerPanel = new scalaLabExplorer(); 
        explorerPanel.setLayout(new BorderLayout());
        explorerPanel.buildClassScriptPathsTree();
        
          
        JPanel  textPanelExplorerDirs = new JPanel(new BorderLayout());  // up panel containing label text
        java.text.DecimalFormat fmt = new java.text.DecimalFormat("0.00");
        String  mem =  fmt.format( (double)GlobalValues.rt.freeMemory()/1000000);
        String dispStr = "Available memory : "+mem+"MB.  ";
         GlobalValues.availMemLabel  = new JLabel(dispStr);
         GlobalValues.availMemLabel .setFont(new Font("Arial", Font.BOLD, 12));
         textPanelExplorerDirs.add(GlobalValues.availMemLabel, BorderLayout.EAST);
        
        
        JPanel  textPanelExplorerBrowser = new JPanel(new BorderLayout());  // up panel containing label text
        JLabel  labelExplorerBrowser = new JLabel("scalaLab explorer: edit, compile, run, create, delete files");
         labelExplorerBrowser.setFont(new Font("Arial", Font.BOLD, 12));
        textPanelExplorerBrowser.add(labelExplorerBrowser, BorderLayout.EAST);
         
        JPanel descriptionPanel = new JPanel(new BorderLayout());
        descriptionPanel.add(textPanelExplorerDirs, BorderLayout.WEST);
        descriptionPanel.add(textPanelExplorerBrowser, BorderLayout.EAST);
         
        JPanel  explorerLabelPanel = new JPanel(new BorderLayout());
        explorerLabelPanel.add(descriptionPanel, BorderLayout.NORTH);
        explorerLabelPanel.add(explorerPanel, BorderLayout.SOUTH);
        
        pathsScrollPane = new JScrollPane(explorerLabelPanel);
        
        horizDividerLoc =  (int)(0.4*xSizeMainFrame);  // controls Explorer vs (History and Variables panels)
        JSplitPane varsHistPathsPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, historyVarsPanel, pathsScrollPane);
        varsHistPathsPane.setDividerLocation(horizDividerLoc);
        
        vertDividerLocConsole = (int)(0.3*ySizeMainFrame);  // controls the command input console size
        pathsScrollPane.setSize(horizDividerLoc, vertDividerLocConsole);
        
        outerPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, varsHistPathsPane, consPane);
        outerPane.setDividerLocation(vertDividerLocConsole);
        
        varsScrolPane.setToolTipText("Displayed scalaLab's workspace variables. Use F2 to toggle displaying. Current state is: display = "+GlobalValues.displayScalaSciBindingGlobal+"  Use F5 for update");
        uiTabbedPane.setComponentAt(GlobalValues.mainTab, outerPane);  
     
        
        // construct an explicit focus event in order to display the cursor at the input console
        FocusEvent fe = new FocusEvent(scalalabConsole, FocusEvent.FOCUS_GAINED);
        scalalabConsole.dispatchEvent(fe);    
        
        break;


            case GlobalValues.javaHelpTab:   // Java help tab
             EditorPaneHTMLHelp   helpJavaEditorPane = new  EditorPaneHTMLHelp(JavaHelpStr, "Java Help");
             helpJavaEditorPane.setSize((int)(0.8*GlobalValues.scalalabMainFrame.getWidth()), (int)(0.8*GlobalValues.scalalabMainFrame.getHeight()));
             helpJavaEditorPane.setLocation(GlobalValues.scalalabMainFrame.getLocation());
             helpJavaEditorPane.setVisible(true);
             //uiTabbedPane.setComponentAt(GlobalValues.javaHelpTab,  helpJavaEditorPane);

                 break;
                    

                case GlobalValues.scalaHelpTab: // Scala help
        try {
            try {
                // Scala help
                Desktop.getDesktop().browse(new URI(ScalaHelpStr));
            } catch (URISyntaxException ex) {
                Logger.getLogger(scalaLab.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException ex) {
            Logger.getLogger(scalaLab.class.getName()).log(Level.SEVERE, null, ex);
        }
         
         /*
             EditorPaneHTMLHelp   helpScalaEditorPane = new  EditorPaneHTMLHelp(scalaHelpStr, "Scala Help");
             helpScalaEditorPane.setSize((int)(0.8*GlobalValues.scalalabMainFrame.getWidth()), (int)(0.8*GlobalValues.scalalabMainFrame.getHeight()));
             helpScalaEditorPane.setLocation(GlobalValues.scalalabMainFrame.getLocation());
             helpScalaEditorPane.setVisible(true);
*/
                    break;

                
                case GlobalValues.scalaSciTab:
                    JScrollPane  ScalaSciToolboxesPane =   new JScrollPane(scalaSciToolboxes.handleScalaSciTab());
                    uiTabbedPane.setComponentAt(GlobalValues.scalaSciTab, ScalaSciToolboxesPane  );

                  
                    break;  
                        default: break;
            } 
           
            }                    
                    
        
        public static void updateTree() {
              SwingUtilities.invokeLater(new Runnable() {
     public void run() {  // run in  */
  if (explorerPanel != null)   {
            explorerPanel.removeAll();
             explorerPanel.buildClassScriptPathsTree();
             explorerPanel.revalidate();
                    }
                }
              });
        }
              
          
                
        /**The main console initializer.*/
        public  void InitConsole()
        {
               scalalabConsole = new scalaExec.gui.scalalabConsole();
               scalaExec.Interpreter.GlobalValues.userConsole = scalalabConsole;

               
                       SwingUtilities.invokeLater(new Runnable() {
     public void run() {  // run in  */
                consPanel = new  JPanel();
                consPanel.setLayout(new BorderLayout());
                consPanel.add(scalalabConsole, BorderLayout.CENTER);
                GlobalValues.mainStatusPanel = new JPanel();
                
             tabbedToolbars  = new JTabbedPane();
             GlobalValues.scalaSciTabbedToolBar = tabbedToolbars;
                   
              BasicScalaControlOperationsToolbar basicScalaOpsToolbar = new BasicScalaControlOperationsToolbar();
              MatScalaOperationsToolbar   matScalaOpsToolbar = new MatScalaOperationsToolbar();
              VecScalaOperationsToolbar vecScalaOpsToolbar = new VecScalaOperationsToolbar();
              DoubleArrayScalaOperationsToolbar doubleArrayScalaOpsToolbar = new DoubleArrayScalaOperationsToolbar();
              MatrixScalaOperationsToolbar matrixScalaOpsToolbar = new MatrixScalaOperationsToolbar();
              DoubleDoubleScalaOperationsToolbar doubleDoubleScalaOpsToolbar = new DoubleDoubleScalaOperationsToolbar();
              PlotOperationsToolbar  plotOpsToolbar = new PlotOperationsToolbar();
                
              LAScalaToolbar laOpsToolbar = new LAScalaToolbar();
              laOpsToolbar.setToolTipText("Linear Algebra");
              
              WaveletScalaToolbar   waveletScalaToolbar = new WaveletScalaToolbar();
              waveletScalaToolbar.setToolTipText("Scala Wavelet Analysis Toolbar. At initial state of development yet!!");
              OptimizationScalaToolbar  optimizationScalaToolbar = new OptimizationScalaToolbar();
              optimizationScalaToolbar.setToolTipText("Scala Wizards for performing numerical optimization tasks.  At initial state of development yet!!");
              ODEScalaToolbar odeScalaToolbar = new ODEScalaToolbar();
              odeScalaToolbar.setToolTipText("Scala Wizards for performing ODE numerical solving tasks.  At initial state of development yet!!");
              PDEScalaToolbar pdeScalaToolbar = new PDEScalaToolbar();
              pdeScalaToolbar.setToolTipText("Partial Differential Equations solving tasks");
              SpecialFunctionsToolbar specialFunctionsToolbar = new SpecialFunctionsToolbar();
              specialFunctionsToolbar.setToolTipText("Special Functions");
              
              CalculusScalaToolbar  calculusScalaToolbar = new  CalculusScalaToolbar();
              calculusScalaToolbar.setToolTipText("Scala Wizards for performing Calculus.  At initial state of development yet!!");

              tabbedToolbars.setToolTipText("The Scala toolbar. Use CTRL-T to hide/show it (.. sorry, many toolbar operations are not yet complete ..)");

              tabbedToolbars.addTab("Vec", vecScalaOpsToolbar);
              tabbedToolbars.setToolTipTextAt(0, "1-D Vector Operations (class Vec)");
              tabbedToolbars.addTab("Matrix", matrixScalaOpsToolbar);
              tabbedToolbars.setToolTipTextAt(1, "One indexed  matrix,  i.e.. starts at M(1,1)  (class Matrix)m based on NUMAL library");
              tabbedToolbars.addTab("Mat",  matScalaOpsToolbar);
              tabbedToolbars.setToolTipTextAt(2, "Zero indexed matrix, i.e.. starts at M(0,0),  (class Mat), support library can be switched, e.g. JAMA, EJML, MTJ");
              tabbedToolbars.addTab("[D]", doubleArrayScalaOpsToolbar);
              tabbedToolbars.setToolTipTextAt(3, "1-D Array, i.e. Array[Double]");
              tabbedToolbars.addTab("[[D]]", doubleDoubleScalaOpsToolbar);
              tabbedToolbars.setToolTipTextAt(4, "2-D Array, i.e. Array[Array[Double]], supports NUMAL based one-indexed routines");
              tabbedToolbars.addTab("Control", basicScalaOpsToolbar);
              tabbedToolbars.setToolTipTextAt(5, "Operations for controlling the environment");
              tabbedToolbars.addTab("Plot", plotOpsToolbar);
              tabbedToolbars.setToolTipTextAt(6, "GUI for Plotting Functions ");
              tabbedToolbars.addTab("LinearAlgebra", laOpsToolbar);
              tabbedToolbars.setToolTipTextAt(7, "Linear Algrebra Functions");
              tabbedToolbars.addTab("Optimization", optimizationScalaToolbar);
              tabbedToolbars.setToolTipTextAt(8, "Numerical Optimization of functions");
              tabbedToolbars.addTab("ODE", odeScalaToolbar);
              tabbedToolbars.setToolTipTextAt(9, "Ordinary Differential Equations (ODEs) solvers");
              tabbedToolbars.addTab("PDE", pdeScalaToolbar);
              tabbedToolbars.setToolTipTextAt(10, "Partial Differential Equations (PDEs) solvers");
              tabbedToolbars.addTab("SpecialFunctions", specialFunctionsToolbar);
              tabbedToolbars.setToolTipTextAt(11, "Special Functions toolbar");
              tabbedToolbars.addTab("Calculus", calculusScalaToolbar);
              tabbedToolbars.setToolTipTextAt(12, "Calculus utility routines, e.g. numerical integration, differentiation");
              tabbedToolbars.addTab("Wavelet", waveletScalaToolbar);
              tabbedToolbars.setToolTipTextAt(13, "Wavelet toolbox interface");
              
// create Undocked
              basicScalaOpsToolbar = new BasicScalaControlOperationsToolbar();
              matScalaOpsToolbar = new MatScalaOperationsToolbar();
              vecScalaOpsToolbar = new VecScalaOperationsToolbar();
              doubleArrayScalaOpsToolbar = new DoubleArrayScalaOperationsToolbar();
              matrixScalaOpsToolbar = new MatrixScalaOperationsToolbar();
              doubleDoubleScalaOpsToolbar = new DoubleDoubleScalaOperationsToolbar();
              plotOpsToolbar = new PlotOperationsToolbar();
                
              laOpsToolbar = new LAScalaToolbar();
              laOpsToolbar.setToolTipText("Linear Algebra");
              
              waveletScalaToolbar = new WaveletScalaToolbar();
              waveletScalaToolbar.setToolTipText("Scala Wavelet Analysis Toolbar. At initial state of development yet!!");
              optimizationScalaToolbar = new OptimizationScalaToolbar();
              optimizationScalaToolbar.setToolTipText("Scala Wizards for performing numerical optimization tasks.  At initial state of development yet!!");
              odeScalaToolbar = new ODEScalaToolbar();
              odeScalaToolbar.setToolTipText("Scala Wizards for performing ODE numerical solving tasks.  At initial state of development yet!!");
              pdeScalaToolbar = new PDEScalaToolbar();
              pdeScalaToolbar.setToolTipText("Partial Differential Equations solving tasks");
              specialFunctionsToolbar = new SpecialFunctionsToolbar();
              specialFunctionsToolbar.setToolTipText("Special Functions");
              
              calculusScalaToolbar = new  CalculusScalaToolbar();
              calculusScalaToolbar.setToolTipText("Scala Wizards for performing Calculus.  At initial state of development yet!!");

             tabbedToolbarsUnDocked  = new JTabbedPane();
             
              tabbedToolbarsUnDocked.setToolTipText("The Scala toolbar. Use CTRL-T to hide/show it (.. sorry, many toolbar operations are not yet complete ..)");

              tabbedToolbarsUnDocked.addTab("Vec", vecScalaOpsToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(0, "1-D Vector Operations (class Vec)");
              tabbedToolbarsUnDocked.addTab("Matrix", matrixScalaOpsToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(1, "One indexed  matrix,  i.e.. starts at M(1,1)  (class Matrix)m based on NUMAL library");
              tabbedToolbarsUnDocked.addTab("Mat",  matScalaOpsToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(2, "Zero indexed matrix, i.e.. starts at M(0,0),  (class Mat), support library can be switched, e.g. JAMA, EJML, MTJ");
              tabbedToolbarsUnDocked.addTab("[D]", doubleArrayScalaOpsToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(3, "1-D Array, i.e. Array[Double]");
              tabbedToolbarsUnDocked.addTab("[[D]]", doubleDoubleScalaOpsToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(4, "2-D Array, i.e. Array[Array[Double]], supports NUMAL based one-indexed routines");
              tabbedToolbarsUnDocked.addTab("Control", basicScalaOpsToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(5, "Operations for controlling the environment");
              tabbedToolbarsUnDocked.addTab("Plot", plotOpsToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(6, "GUI for Plotting Functions ");
              tabbedToolbarsUnDocked.addTab("LinearAlgebra", laOpsToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(7, "Linear Algrebra Functions");
              tabbedToolbarsUnDocked.addTab("Optimization", optimizationScalaToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(8, "Numerical Optimization of functions");
              tabbedToolbarsUnDocked.addTab("ODE", odeScalaToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(9, "Ordinary Differential Equations (ODEs) solvers");
              tabbedToolbarsUnDocked.addTab("PDE", pdeScalaToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(10, "Partial Differential Equations (PDEs) solvers");
              tabbedToolbarsUnDocked.addTab("SpecialFunctions", specialFunctionsToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(11, "Special Functions toolbar");
              tabbedToolbarsUnDocked.addTab("Calculus", calculusScalaToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(12, "Calculus utility routines, e.g. numerical integration, differentiation");
              tabbedToolbarsUnDocked.addTab("Wavelet", waveletScalaToolbar);
              tabbedToolbarsUnDocked.setToolTipTextAt(13, "Wavelet toolbox interface");
              

              
              
              GlobalValues.scalaSciTabbedToolBar = tabbedToolbars;
              
                GlobalValues.mainStatusPanel.add(tabbedToolbars);  
                consPanel.add(GlobalValues.mainStatusPanel, BorderLayout.SOUTH);
                add(GlobalValues.mainStatusPanel, BorderLayout.SOUTH);
                consPane = new JScrollPane(consPanel);
                  }
              });
        }

        
         /**The menu initializer.*/
        private void InitJMenuBar(final ActionListener listener)
        {
               SwingUtilities.invokeLater(new Runnable() {

     public void run() {  // run in  */
                mainJMenuBar = new JMenuBar();
                mainJMenuBar.setFont(new Font("Arial", Font.BOLD, 18));
                        
                FileMenu = new JMenu("File");
                FileMenu.setMnemonic('F');
                FileMenu.setToolTipText("File editing, Command history, Variable workspace operations");
                
                editMenu = new JMenu("Edit");
                       
                fileExplorerFocusMenuItem = new JMenuItem(new focusExplorerAction());
                editJMenuItem = new JMenuItem(new editAction());
                editJMenuItem.setIcon(new ImageIcon(editImage));  
                editJMenuItem.setMnemonic('E');
                editJMenuItem.setAccelerator(KeyStroke.getKeyStroke("ctrl E"));
                
                JMenuItem jeditJMenuItem = new JMenuItem(new jeditAction());
                jeditJMenuItem.setIcon(new ImageIcon(editImage));  
                jeditJMenuItem.setMnemonic('J');
                jeditJMenuItem.setAccelerator(KeyStroke.getKeyStroke("ctrl J"));
                
                fileExplorerFocusMenuItem.setMnemonic('X');
                fileExplorerFocusMenuItem.setAccelerator(KeyStroke.getKeyStroke("ctrl X"));
                fileExplorerFocusMenuItem.setToolTipText("Focus on File Tree Explorer in order to perform file operations");

                editDSPJMenuItem = new JMenuItem(new editDSPAction());
                editDSPJMenuItem.setIcon(new ImageIcon(editImage));  
                editDSPJMenuItem.setMnemonic('D');
                
                jeditDSPJMenuItem = new JMenuItem(new editDSPAction());
                jeditDSPJMenuItem.setIcon(new ImageIcon(editImage));  
                jeditDSPJMenuItem.setMnemonic('D');
                
                
                 saveVars = new JMenuItem("Save Variables");
                 saveVars.setEnabled(false);
                 saveVars.setIcon(new ImageIcon(saveImage));
                 saveVars.setToolTipText("Saves the variables that constitute the scalaLab's workspace global context to an external file");
                 saveVars.addActionListener(new java.awt.event.ActionListener() {
                     public void actionPerformed(ActionEvent e) {
     JFileChooser  chooser = new JFileChooser(GlobalValues.workingDir);
     chooser.setDialogTitle("Specify file for saving scalaLab's workspace variables");
     int retVal = chooser.showSaveDialog(GlobalValues.scalalabMainFrame);
     if (retVal == JFileChooser.APPROVE_OPTION) { 
    File selectedFile = chooser.getSelectedFile();
    String saveVarsFile = selectedFile.getAbsolutePath();
                     }
                   }
                 });

                 loadVars = new JMenuItem("Load Variables resetting workspace");
                 loadVars.setEnabled(false);
                 loadVars.setToolTipText("Loads the saved scalaLab's workspace variables from an external file");
                 loadVars.addActionListener(new java.awt.event.ActionListener() {
                     public void actionPerformed(ActionEvent e) {
     JFileChooser  chooser = new JFileChooser(GlobalValues.workingDir);
     chooser.setDialogTitle("Specify file for loading scalaLab's variables");
     int retVal = chooser.showOpenDialog(GlobalValues.scalalabMainFrame);
     if (retVal == JFileChooser.APPROVE_OPTION) { 
    File selectedFile = chooser.getSelectedFile();
    String loadVarsFile = selectedFile.getAbsolutePath();
                     }
                   }
                 });
                
                 saveHistoryItem= new JMenuItem("Save Command History");
                 saveHistoryItem.setToolTipText("Saves the buffer of the issued commands to an external file");
                 saveHistoryItem.addActionListener(new saveHistoryAction());
    
                 loadHistoryItem= new JMenuItem("Load Command History");
                 loadHistoryItem.setToolTipText("Loads the buffer of the issued commands from an external file");
                 loadHistoryItem.addActionListener(new loadHistoryAction());
                         
                 displayHistoryItem= new JMenuItem("Display Command History");
                 displayHistoryItem.setToolTipText("Displays the buffer of the issued commands");
                 displayHistoryItem.addActionListener(new displayHistoryAction());
              
                    
                 clearHistoryItem= new JMenuItem("Clear Command History");
                 clearHistoryItem.setToolTipText("Clears the buffer of the issued commands");
                 clearHistoryItem.addActionListener(new clearHistoryAction());
                     
         
                 
    appendVars = new JMenuItem("Load Variables appending to the workspace");
    appendVars.setEnabled(false);
    appendVars.setToolTipText("... loads new variables and keeps also the current contents of the workspace");
    appendVars.addActionListener(new java.awt.event.ActionListener() {
                     public void actionPerformed(ActionEvent e) {
     JFileChooser  chooser = new JFileChooser(GlobalValues.workingDir);
     chooser.setDialogTitle("Browse filesystem for the file to load the variables appending them to the existing ones");
     int retVal = chooser.showOpenDialog(GlobalValues.scalalabMainFrame);
     if (retVal == JFileChooser.APPROVE_OPTION) { 
    File selectedFile = chooser.getSelectedFile();
    String appendVarsFile = selectedFile.getAbsolutePath();
                     }
                   }
                 });
                
                 
                 
                 
                
                exitJMenuItem = new JMenuItem("Exit");
                exitJMenuItem.addActionListener(new java.awt.event.ActionListener() {
                    public void actionPerformed(ActionEvent e) {
   closeGUI();
                   }});
                

                editMenu.add(editJMenuItem);
                editMenu.add(editDSPJMenuItem);
                
                editMenu.add(jeditJMenuItem);
                
                FileMenu.add(fileExplorerFocusMenuItem);
                FileMenu.add(saveVars);
                FileMenu.add(loadVars);
                FileMenu.add(appendVars);
                FileMenu.add(saveHistoryItem);
                FileMenu.add(loadHistoryItem);
                FileMenu.add(displayHistoryItem);
                FileMenu.add(clearHistoryItem);
                FileMenu.add(exitJMenuItem);
              
                    

                ProjectMenu = new JMenu("Project ");
                ProjectMenu.setMnemonic('P');
                ProjectMenu.setToolTipText("Projects allow to configure the paths and the environment according to each ScalaSci application"); 

                
                JavaMenu = new JMenu("Java ");
                JavaMenu.setMnemonic('J');
                JavaMenu.setToolTipText("Java standard projects");
                
                ScalaMenu = new JMenu("Scala ");
                ScalaMenu.setMnemonic('S');
                ScalaMenu.setToolTipText("Scala standard projects");

             
                CompileScriptsOnScalaLabClasspathJItem = new JMenuItem(new compileScalaSciScriptsOnScalaSciClasspathAction());
                CompileScriptsOnScalaLabClasspathJItem.setEnabled(false);
                scalaSciParametersJItem = new JMenuItem(new scalalabScriptsPathsAction());
                
                ConfigureScalaJItem = new JMenuItem(new configureScalaInterpreterAction());
                ConfigureScalaJItem.setEnabled(false);

                 NewProjectJItem = new JMenuItem(new newProjectAction());
                 NewProjectJItem.setEnabled(false);
                 OpenProjectJItem = new JMenuItem(new openProjectAction());
                 OpenProjectJItem.setToolTipText("Allows to open a ScalaSci Project . "+
                         "Configures the paths and the environment according to the project specification");
                 OpenProjectJItem.setEnabled(false);
                 SaveProjectJMenuItem = new JMenuItem(new saveProjectAction());
                 SaveProjectJMenuItem.setEnabled(false);
                 CloseProjectJMenuItem = new JMenuItem(new closeProjectAction());
                 CloseProjectJMenuItem.setEnabled(false);
                 
                 swingConsoleMenu = new JMenu("SwingScalaConsole ");
                 swingConsoleMenu.setToolTipText("A Swing based interface to the Scala Interpreter adapted from Hanns Holger Rutz, with nice syntax coloring ");
                 swingConsoleMenuItemJAMA = new JMenuItem("Open Scala Interpreter Swing  Console  for JAMA based zero-indexed Matrix library");
                 swingConsoleMenu.add(swingConsoleMenuItemJAMA);
                 swingConsoleMenuItemJAMA.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
               GlobalValues.libraryToUseForConsole = GlobalValues.JAMAMat;         
               de.sciss.scalainterpreter.Main.main(null);  
                    }
                });
               
                   swingConsoleMenuItemEJML = new JMenuItem("Open Scala Interpreter Swing Console for EJML based zero-index Matrix library");
                 swingConsoleMenu.add(swingConsoleMenuItemEJML);
                 swingConsoleMenuItemEJML.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
               GlobalValues.libraryToUseForConsole = GlobalValues.EJMLMat;         
               de.sciss.scalainterpreter.Main.main(null);  
                    }
                });
               
                 JMenuItem simpleJavaClassFile = new JMenuItem(new simpleJavaApplAction());
                 JMenuItem simpleJavaClassFileUsingScalaLab = new JMenuItem(new simpleJavaApplUsingScalaLabAction());
                 JMenuItem simpleJavaClassFileUsingScalaLabBioJava = new JMenuItem(new simpleJavaApplUsingScalaLabBioJavaAction());

                 JMenuItem simpleScalaClassFile = new JMenuItem(new simpleScalaApplAction());
                 JMenuItem simpleScalaClassFileUsingScalaLab = new JMenuItem(new simpleScalaApplUsingScalaLabAction());
                 JMenuItem simpleScalaClassFileUsingScalalabBioJava = new JMenuItem(new simpleScalaApplUsingScalaLabBioJavaAction());
                 JMenuItem ScalaClassWithCompanionObject = new JMenuItem(new scalaClassWithCompanionObject() );
                 JMenuItem ScalaSingletonObject = new JMenuItem(new scalaStandAloneObject());
                    
                 JavaMenu.add(simpleJavaClassFile);
                 JavaMenu.add(simpleJavaClassFileUsingScalaLab);
                 JavaMenu.add(simpleJavaClassFileUsingScalaLabBioJava);
                 JavaMenu.setMnemonic('J');

                 ScalaMenu.add(ConfigureScalaJItem);
                 ScalaMenu.add(simpleScalaClassFile);
                 ScalaMenu.add(simpleScalaClassFileUsingScalaLab);
                 ScalaMenu.add(simpleScalaClassFileUsingScalalabBioJava);
                 ScalaMenu.add(ScalaClassWithCompanionObject);
                 ScalaMenu.add(ScalaSingletonObject);
                 ScalaMenu.setMnemonic('S');
                 
            
                 ProjectMenu.add(CompileScriptsOnScalaLabClasspathJItem);
                 ProjectMenu.setMnemonic('P');
                 ProjectMenu.add(NewProjectJItem);
                 ProjectMenu.add(OpenProjectJItem);
                 ProjectMenu.add(SaveProjectJMenuItem);
                 ProjectMenu.add(CloseProjectJMenuItem);
                 
                
                confMenu = new JMenu("ScalaSci Configuration", true);
                confMenu.setMnemonic('G');        
                //ImageIcon configIcon = new ImageIcon(scalalabPathsConfigImage);
                varsConfJMenuItem = new JMenuItem("scalaLab Paths Configuration"); //, configIcon);
                varsConfJMenuItem.addActionListener(new scalalabScriptsPathsAction());
                
                controlMainToolbarJMenuItem = new JMenuItem(new controlMainToolBarAction());
                controlMainToolbarJMenuItem.setAccelerator(KeyStroke.getKeyStroke("ctrl T"));
              
                resetInterpreterJMenuItem = new JMenuItem(new resetInterpreterAction());
                resetInterpreterJMenuItem.setAccelerator(KeyStroke.getKeyStroke("ctrl R"));
                
                adjustFontMenuItem = new JMenuItem("Adjust Fonts"); // configIcon);
                adjustFontMenuItem.addActionListener(new FontAdjusterAction());
                
                
                adjustLookAndFeelMenuItem = new JMenuItem("Configure Look and Feel"); //, configIcon);
                adjustLookAndFeelMenuItem.addActionListener(new LookAndFeelAdjusterAction());
                loadConfParamsJMenuItem = new JMenuItem(new loadConfigAction());
                saveConfParamsJMenuItem = new JMenuItem(new saveConfigAction());
                
                       
                browseFileSysForPathsJMenuItem = new JMenuItem("Browse File system For Paths"); //, new ImageIcon(pathsConfigImage));
                browseFileSysForPathsJMenuItem.addActionListener(new browseFileSysForPaths());
                
                
                browseClassesJMenuItem = new JMenuItem(new browseJavaClassesAction());
                browseClassesJMenuItem.setIcon(new ImageIcon(sunJavaImage));
                
                promptJMenuItem = new JMenuItem(new promptConfigAction());
                promptJMenuItem.setAccelerator(KeyStroke.getKeyStroke("ctrl D"));
              
                outputConsoleJMenuItem = new JMenuItem(new consoleOutputConfigAction());
                
                configAlphaParamJMenuItem = new JMenuItem(new configAlphaAction());
                configAlphaParamJMenuItem.setEnabled(false);
                
                confMenu.add(scalaSciParametersJItem);
                confMenu.add(loadConfParamsJMenuItem);
                confMenu.add(saveConfParamsJMenuItem);
                confMenu.add(controlMainToolbarJMenuItem);
                confMenu.add(resetInterpreterJMenuItem);
                confMenu.add(browseFileSysForPathsJMenuItem);
                confMenu.add(adjustFontMenuItem);
                confMenu.add(adjustLookAndFeelMenuItem);
                confMenu.add(promptJMenuItem);
                confMenu.add(outputConsoleJMenuItem);
                confMenu.add(configAlphaParamJMenuItem);
                
            
                
                searchMenu = new JMenu("Search", true);
                searchMenu.setEnabled(false);
                searchClassesJMenuItem = new JMenuItem("Search For Class with regular expression");
                searchClassesJMenuItem.addActionListener(
                         new java.awt.event.ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        SwingUtilities.invokeLater(new Runnable() {
            public void run() {  // run in  EDT context */
                        Vector  patternMatches = searchForClassWithRegularExpression("(l)\\w*");
                        for (int k=0; k<patternMatches.size(); k++)
                          System.out.println("found : "+(String)patternMatches.elementAt(k));
                    }
                         });
                    }
                });
                searchClassesJMenuItem.setEnabled(false);
                searchMenu.add(searchClassesJMenuItem);
                
                        
                ImageIcon mathematicsIcon = new ImageIcon(userFunctionsImage);
                trigonometricFunctionsJMenuItem = new JMenuItem("Trigonometric Functions");
                trigonometricFunctionsJMenuItem.setIcon(mathematicsIcon);
                trigonometricFunctionsJMenuItem.addActionListener(
                      new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
        SwingUtilities.invokeLater(new Runnable() {
     public void run() {  // run in  EDT context */
     TrigonometricFunctionToolbar trigonometricToolbar = new TrigonometricFunctionToolbar();
        }
     });
   }
}
                        );
                
                
                toolboxesToolbarJMenuItem = new JMenuItem("Toolboxes (?)");
                toolboxesToolbarJMenuItem.addActionListener(
                        new java.awt.event.ActionListener() {
                    public void actionPerformed(ActionEvent e) {
        SwingUtilities.invokeLater(new Runnable() {
     public void run() {  // run in  EDT context */
             ToolboxesToolbar toolboxesToolbar = new ToolboxesToolbar();
     }
        });
                    }
                });
                
                
                wizardsMenu = new JMenu("Wizards");
                wizardsMenu.setMnemonic('W');
                
                wizardsMenu.setToolTipText("The Wizards menu allows to build almost automatically the code for categories of applications, e.g. ODE solvers");
                
                wizardsScalaSciScalaJMenuItem = new JMenuItem(new ODEWizardscalaSciScalaAction());
                wizardsScalaSciScalaJMenuItem.setToolTipText("Builds a ScalaSci ODE Solver with a full Scala-based implementation ");
                wizardsScalaSciScalaJMenuItem.setIcon(new ImageIcon(ODEWizardImage));
                wizardsMenu.add(wizardsScalaSciScalaJMenuItem);
 
                wizardsScalaSciJMenuItem = new JMenuItem(new ODEWizardscalaSciAction());
                wizardsScalaSciJMenuItem.setToolTipText("Builds a ScalaSci ODE Solver with the ODEs implemented with Java code");
                wizardsScalaSciJMenuItem.setIcon(new ImageIcon(ODEWizardImage));
                wizardsMenu.add(wizardsScalaSciJMenuItem);
 
                
                    
        examplesMenu = new JMenu("Demos  ", true);
        examplesMenu.setToolTipText("Examples and Demos ");
        
        
        
        ScalaSciExamplesHelpJMenuItem = new JMenuItem("ScalaSci  Examples");
        ScalaSciExamplesHelpJMenuItem.addActionListener(new scalaSciExamplesAction());
        //ScalaExamplesHelpJMenuItem.setIcon(new ImageIcon(scalaImage));

     /*   FastSciExamplesHelpJMenuItem = new JMenuItem("FastSci  Examples");
        FastSciExamplesHelpJMenuItem.addActionListener(new fastSciExamplesAction());
*/
        ScalaExamplesHelpJMenuItem = new JMenuItem("Scala Examples");
        ScalaExamplesHelpJMenuItem.addActionListener(new scalaExamplesAction());
        
        ScalaExamplesPlotHelpJMenuItem = new JMenuItem("ScalaSci  Plotting Examples");
        ScalaExamplesPlotHelpJMenuItem.addActionListener(new scalaSciExamplesPlottingAction());
        //ScalaExamplesPlotHelpJMenuItem.setIcon(new ImageIcon(scalaImage));
       
        JMenuItem VisADExamplesPlotHelpJMenuItem = new JMenuItem("VisAD Scientific Visualization Graphics Toolbox  Examples");
        VisADExamplesPlotHelpJMenuItem.addActionListener(new VisADExamplesPlottingAction());
       
        JMenuItem JavaSGTExamplesPlotHelpJMenuItem = new JMenuItem("Scientific Graphics Toolbox  Plotting Examples");
        JavaSGTExamplesPlotHelpJMenuItem.addActionListener(new JavaSGTExamplesPlottingAction());
       
        ScalaExamplesODEHelpJMenuItem = new JMenuItem("ScalaSci  ODE Examples (use: java  -Xss10m -Xms200m -Xmx1000m -jar scalalab.jar, to avoid stack overflow)");
        ScalaExamplesODEHelpJMenuItem.addActionListener(new scalaSciODEExamplesAction());
        //ScalaExamplesODEHelpJMenuItem.setIcon(new ImageIcon(scalaImage));
        
        
        ScalaExamplesWaveletHelpJMenuItem = new JMenuItem("ScalaSci  Wavelet Examples");
        ScalaExamplesWaveletHelpJMenuItem.addActionListener(new scalaSciWaveletExamplesAction());
        //ScalaExamplesWaveletHelpJMenuItem.setIcon(new ImageIcon(scalaImage));

        ScalaExamplesJOONEHelpJMenuItem = new JMenuItem("ScalaSci JOONE Examples");
        ScalaExamplesJOONEHelpJMenuItem.addActionListener(new scalaSciJOONEExamplesAction());

        ScalaExamplesBioJavaHelpJMenuItem = new JMenuItem("BioJava Examples in Java");
        ScalaExamplesBioJavaHelpJMenuItem.addActionListener(new scalaSciBioJavaExamplesAction());

        ScalaExamplesWEKAHelpJMenuItem = new JMenuItem("ScalaSci  WEKA Examples");
        ScalaExamplesWEKAHelpJMenuItem.addActionListener(new scalaSciWEKAExamplesAction());

        ScalaExamplesLAHelpJMenuItem = new JMenuItem("ScalaSci  Linear Algebra Examples");
        ScalaExamplesLAHelpJMenuItem.addActionListener(new scalaSciExamplesLAAction());
        ScalaExamplesLAHelpJMenuItem.setEnabled(true);
        //ScalaExamplesLAHelpJMenuItem.setIcon(new ImageIcon(scalaImage));
         
        examplesMenu.setMnemonic('e');
        examplesMenu.add(ScalaSciExamplesHelpJMenuItem);
        // examplesMenu.add(FastSciExamplesHelpJMenuItem);
        examplesMenu.add(ScalaExamplesPlotHelpJMenuItem);
        examplesMenu.add(VisADExamplesPlotHelpJMenuItem);
        examplesMenu.add(JavaSGTExamplesPlotHelpJMenuItem);
        examplesMenu.add(ScalaExamplesODEHelpJMenuItem);
        examplesMenu.add(ScalaExamplesWaveletHelpJMenuItem);
        examplesMenu.add(ScalaExamplesBioJavaHelpJMenuItem);
        examplesMenu.add(ScalaExamplesJOONEHelpJMenuItem);
        examplesMenu.add(ScalaExamplesWEKAHelpJMenuItem);
        examplesMenu.add(ScalaExamplesLAHelpJMenuItem);
        examplesMenu.add(ScalaExamplesHelpJMenuItem);
        
             
             autocompletionJMenuItem = new JMenuItem("Code AutoCompletion -- F1,  Variable Autocompletion -- TAB ");
             autocompletionJMenuItem.addActionListener( 
                        new java.awt.event.ActionListener() {
                   public void actionPerformed(ActionEvent e) { 
                JOptionPane.showMessageDialog(null, "Pressing F1 scalaLab will try to autocomplete your code expression, with TAB the autocompletion applies to the code variables", "AutoCompletion", JOptionPane.INFORMATION_MESSAGE);
               }
             });

             autocompletionRegExJMenuItem = new JMenuItem("Code AutoCompletion with Regular Expressions-- F3");
             autocompletionRegExJMenuItem.addActionListener( new scalaExec.scalaLab.autoCompletionRegExHelpAction());
               
             JavaSciHelpJMenuItem = new JMenuItem("Java API  JavaHelp");
             JavaSciHelpJMenuItem.setToolTipText("Extensive help for the Java 6 SDK API platform");
             JavaSciHelpJMenuItem.addActionListener(new java.awt.event.ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if  (GlobalValues.JavaCSHObject==null) {
                            GlobalValues.JavaCSHObject = new scalaExec.scalaLab.CSHObject();
                            GlobalValues.JavaCSHObject.setHelpSystem(GlobalValues.JavaHelpSetName);   // set the help system to Java JDK help
                            GlobalValues.JavaCSHObject.setConsoleHelp("top");
                            GlobalValues.JavaCSHObject.displayTheHelp();                    
                     }
                        else
            GlobalValues.JavaCSHObject.displayTheHelp();                    }
                }); 

                ScalaHelpJMenuItem = new JMenuItem("Scala API  JavaHelp");
             ScalaHelpJMenuItem.setToolTipText("Extensive help for the Scala Language");
             ScalaHelpJMenuItem.addActionListener(new java.awt.event.ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if  (GlobalValues.ScalaCSHObject==null) {
                            GlobalValues.ScalaCSHObject = new scalaExec.scalaLab.CSHObject();
                            GlobalValues.ScalaCSHObject.setHelpSystem(GlobalValues.ScalaHelpSetName);   // set the help system to Scala help
                            GlobalValues.ScalaCSHObject.setConsoleHelp("top");
                            GlobalValues.ScalaCSHObject.displayTheHelp();
                     }
                        else
            GlobalValues.ScalaCSHObject.displayTheHelp();                    }
                });

             JMenuItem EJMLJMenuItem = new JMenuItem("Efficient Java Matrix Library JavaHelp");
             EJMLJMenuItem.setToolTipText("EJML help: Provides help for the Efficient Java Matrix Library. Use Console's pop-up menu to activate EJML");
             EJMLJMenuItem.addActionListener(new java.awt.event.ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if  (GlobalValues.EJMLCSHObject==null) {
                            GlobalValues.EJMLCSHObject = new scalaExec.scalaLab.CSHObject();
                            GlobalValues.EJMLCSHObject.setHelpSystem(GlobalValues.EJMLHelpSetName);   
                            GlobalValues.EJMLCSHObject.setConsoleHelp("top");
                            GlobalValues.EJMLCSHObject.displayTheHelp();                    
                            
                     }
                        else
            GlobalValues.EJMLCSHObject.displayTheHelp();                    }
                }); 

                JMenuItem BioJavaJMenuItem = new JMenuItem("BioJava JavaHelp");
             BioJavaJMenuItem.setToolTipText("BioJava help: Requires the biojavaHS.jar at the /lib folder");
             BioJavaJMenuItem.addActionListener(new java.awt.event.ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if  (GlobalValues.BioJavaCSHObject==null) {
                            GlobalValues.BioJavaCSHObject = new scalaExec.scalaLab.CSHObject();
                            GlobalValues.BioJavaCSHObject.setHelpSystem(GlobalValues.BioJavaHelpSetName);
                            GlobalValues.BioJavaCSHObject.setConsoleHelp("top");
                            GlobalValues.BioJavaCSHObject.displayTheHelp();                    
                            
                     }
                        else
            GlobalValues.BioJavaCSHObject.displayTheHelp();                    }
                }); 

                
             jLabIDEJMenuItem = new JMenuItem("scalaLab IDE JavaHelp");
             jLabIDEJMenuItem.setEnabled(false);
             jLabIDEJMenuItem.setToolTipText("Extensive help on the scalaLab IDE ");
             jLabIDEJMenuItem.addActionListener(new java.awt.event.ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if  (GlobalValues.scalalabIDEHelpObject == null) {
                            GlobalValues.scalalabIDEHelpObject = new scalaExec.scalaLab.CSHObject();
                            GlobalValues.scalalabIDEHelpObject.setHelpSystem(GlobalValues.scalalabIDEHelpSetName);   // set the help system to Java JDK help
                            GlobalValues.scalalabIDEHelpObject.setConsoleHelp("top");
                            GlobalValues.scalalabIDEHelpObject.displayTheHelp();                   
                }
                          else
    GlobalValues.scalalabIDEHelpObject.displayTheHelp();   // set the help system to Java JDK help
                    }
                }); 
                

             
             bufferedLineInputJMenuItem = new JMenuItem("Switch Buffered / Line Input  -- F4 ");
             bufferedLineInputJMenuItem.addActionListener( 
                        new java.awt.event.ActionListener() {
                   public void actionPerformed(ActionEvent e) { 
                JOptionPane.showMessageDialog(null, 
           "Pressing F4 scalaLab switches between buffered and single line processing. Mutliple lines of code can be accumulated in buffered mode. Switch to line mode to execute them.", 
                        "Switch Buffered / Line Mode", JOptionPane.INFORMATION_MESSAGE);
               }
             });

     
        
                watchVariablesUpdateJMenuItem = new JMenuItem("Switch ON/OFF the display of Workspace Variables Binding -- F2 ");
             watchVariablesUpdateJMenuItem.addActionListener( 
                        new java.awt.event.ActionListener() {
                   public void actionPerformed(ActionEvent e) { 
                 JOptionPane.showMessageDialog(null, "Pressing F2 toggles the global flag for displaying  the binded workspace variables. Use ';' at the end of a particular command to suppress its output.", "Workspace Variables Binding Display", JOptionPane.INFORMATION_MESSAGE);
               }
             });
             
             
             
             scalaCellsMenu = new JMenu("Scala Code Cells");
             openScalaCellsJMenuItem = new JMenuItem("Open Scala Cells Environment");
             openScalaCellsJMenuItem.addActionListener(new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
             new scalalab.scalalab(null);
                    }
                });
             
                helpMenu = new JMenu("Help", true);
                helpMenu.setMnemonic('h');
                 
             GettingStartedJMenuItem  = new JMenuItem("Getting Started with scalaLab - A scalaLab Tutorial");
             GettingStartedJMenuItem.setFont(new Font("Arial", Font.BOLD, 14 ));
             GettingStartedJMenuItem.setToolTipText("Provides an introduction to the scalaLab environment with many examples");
             GettingStartedJMenuItem.addActionListener(new java.awt.event.ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        if  (GlobalValues.GettingStartedCSHObject == null) {
                            GlobalValues.GettingStartedCSHObject  = new scalaExec.scalaLab.CSHObject();
                            GlobalValues.GettingStartedCSHObject.setHelpSystem(GlobalValues.scalalabIntroHelpSetName);  
                            GlobalValues.GettingStartedCSHObject.setConsoleHelp("top");
                            GlobalValues.GettingStartedCSHObject.displayTheHelp();                    
                     }
                        else
            GlobalValues.GettingStartedCSHObject.displayTheHelp();                    }
                }); 
    
            ScalaLabArchitectureJMenuItem  = new JMenuItem("ScalaLab Architecture");
            ScalaLabArchitectureJMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
        EditorPaneHTMLHelp  inPlaceHelpPane = new EditorPaneHTMLHelp("scalalabArchitecture.html");
        inPlaceHelpPane.setSize(GlobalValues.figFrameSizeX, GlobalValues.figFrameSizeY);
        inPlaceHelpPane.setLocation(GlobalValues.sizeX/4, GlobalValues.sizeY/4);
        inPlaceHelpPane.setVisible(true);
    
            }
        });
        
           JMenuItem speedingNumericalScriptsJMenuItem  = new JMenuItem("Speeding Numerical Scripts within the Scala Interpreter");
           speedingNumericalScriptsJMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
        EditorPaneHTMLHelp  inPlaceHelpPane = new EditorPaneHTMLHelp("SpeedingScalaInterpreter.html");
        inPlaceHelpPane.setSize(GlobalValues.figFrameSizeX, GlobalValues.figFrameSizeY);
        inPlaceHelpPane.setLocation(GlobalValues.sizeX/4, GlobalValues.sizeY/4);
        inPlaceHelpPane.setVisible(true);
    
            }
        });
        
            JMenuItem ScalaLabBuildFromSourcesJMenuItem  = new JMenuItem("Building ScalaLab From Sources");
            ScalaLabBuildFromSourcesJMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
        EditorPaneHTMLHelp  inPlaceHelpPane = new EditorPaneHTMLHelp("BuildingScalaLab.html");
        inPlaceHelpPane.setSize(GlobalValues.figFrameSizeX, GlobalValues.figFrameSizeY);
        inPlaceHelpPane.setLocation(GlobalValues.sizeX/4, GlobalValues.sizeY/4);
        inPlaceHelpPane.setVisible(true);
    
            }
        });
             
            JMenuItem ScalaLabLibrariesBuildFromSourcesJMenuItem  = new JMenuItem("Building ScalaLab Basic Libraries From Sources");
            ScalaLabLibrariesBuildFromSourcesJMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
        EditorPaneHTMLHelp  inPlaceHelpPane = new EditorPaneHTMLHelp("BuildingLibrariesForScalaLab.html");
        inPlaceHelpPane.setSize(GlobalValues.figFrameSizeX, GlobalValues.figFrameSizeY);
        inPlaceHelpPane.setLocation(GlobalValues.sizeX/4, GlobalValues.sizeY/4);
        inPlaceHelpPane.setVisible(true);
    
            }
        });
                JMenuItem     ScalaLabResourcesJMenuItem  = new JMenuItem("The standard Java Scientific Libraries in ScalaLab"); 
            ScalaLabResourcesJMenuItem.addActionListener(new ActionListener() {
               public void actionPerformed(ActionEvent e) {
       EditorPaneHTMLHelp  inPlaceHelpPane = new EditorPaneHTMLHelp("ScalaLabBooks.html");
        inPlaceHelpPane.setSize(GlobalValues.figFrameSizeX, GlobalValues.figFrameSizeY);
        inPlaceHelpPane.setLocation(GlobalValues.sizeX/4, GlobalValues.sizeY/4);
        inPlaceHelpPane.setVisible(true);
          }
                });
            
             scalaCellsMenu.add(openScalaCellsJMenuItem);
             scalaCellsMenu.setToolTipText("The Scala Code Cells environment permits to execute code in separate cells");
             
           
                JavaHelpMenu = new JMenu("JavaHelp", true);
                JavaHelpMenu.setToolTipText("Provides help on basic components (e.g. Java,  Scala)  using the JavaHelp system");
                        
                
                helpMenu.add(GettingStartedJMenuItem);
                helpMenu.add(ScalaLabArchitectureJMenuItem);
                helpMenu.add(speedingNumericalScriptsJMenuItem);
                helpMenu.add(ScalaLabBuildFromSourcesJMenuItem);
                helpMenu.add(ScalaLabLibrariesBuildFromSourcesJMenuItem);
                helpMenu.add(ScalaLabResourcesJMenuItem);
                helpMenu.add(autocompletionJMenuItem);
                helpMenu.add(autocompletionRegExJMenuItem);
                helpMenu.add(bufferedLineInputJMenuItem);
                
                helpMenu.add(watchVariablesUpdateJMenuItem);
                
                JMenuItem cshJMenuItem = new JMenuItem("Help OnItem ");
                cshJMenuItem.setEnabled(false);
	        cshJMenuItem.addActionListener(new CSH.DisplayHelpAfterTracking(GlobalValues.scalalabIDEHelpObject.theHB));
	    
                JavaHelpMenu.add(JavaSciHelpJMenuItem);
                JavaHelpMenu.add(ScalaHelpJMenuItem);
                JavaHelpMenu.add(EJMLJMenuItem);
                JavaHelpMenu.add(BioJavaJMenuItem);
                JavaHelpMenu.add(jLabIDEJMenuItem);
                JavaHelpMenu.add(cshJMenuItem);
                
                basicHelpJMenuItem = new JMenuItem("Basic Commands");
                basicHelpJMenuItem.addActionListener(
                        new java.awt.event.ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
  new basicCommandsHelper();
                    }
                });

                memoryHelpJMenuItem = new JMenuItem("Available memory - How to icrease");
                memoryHelpJMenuItem.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
 	 String  mem =  GlobalValues.availMemFormat.format( (double)GlobalValues.rt.freeMemory()/1000000);
         String dispStr = "Available memory is : "+mem+"MB.  To increase it start ScalaLab with:  java -Xss10m -Xms200m -Xmx1000m -jar scalalab.jar";
         JOptionPane.showMessageDialog(null,  dispStr,  "Available memory", JOptionPane.INFORMATION_MESSAGE);  
                    }
                });
                
                aboutHelpJMenuItem = new JMenuItem("About...");
                
                aboutHelpJMenuItem.addActionListener( 
          new java.awt.event.ActionListener() {
     public void actionPerformed(java.awt.event.ActionEvent evt) {
                        JPanel  aboutJLab = new AboutScalaLab();
    	 		EffectsDialog   aboutDialog = new EffectsDialog(GlobalValues.scalalabMainFrame, aboutJLab, "About scalaLab ", 1 );
                        installInLayeredPane(aboutDialog);
                        aboutDialog.setLocation(50, 50);
                        aboutDialog.setVisible(true);
                            }
 });
     
 
                helpMenu.add(basicHelpJMenuItem);
                helpMenu.add(memoryHelpJMenuItem);
                helpMenu.add(aboutHelpJMenuItem);
                helpMenu.setMnemonic('h');
                
                mainJMenuBar.add(FileMenu);
                mainJMenuBar.add(editMenu);
                mainJMenuBar.add(ProjectMenu);
                mainJMenuBar.add(JavaMenu);
                mainJMenuBar.add(ScalaMenu);
            
                mainJMenuBar.add(scalaCellsMenu);
                mainJMenuBar.add(swingConsoleMenu);
                
                mainJMenuBar.add(confMenu);
                mainJMenuBar.add(searchMenu);
                mainJMenuBar.add(wizardsMenu);
                mainJMenuBar.add(examplesMenu);
                mainJMenuBar.add(JavaHelpMenu);
                mainJMenuBar.add(helpMenu);
                
                        
                mainJMenuBar.setOpaque(true);
                myId.setJMenuBar(mainJMenuBar);
              }
               });
               
           
                   
        }

    public  void installInLayeredPane(JComponent component) {
        JLayeredPane layeredPane = getRootPane().getLayeredPane();
        layeredPane.add(component, JLayeredPane.PALETTE_LAYER, 20);
        Dimension size = component.getPreferredSize();
        component.setSize(size);
        component.setLocation((getWidth() - size.width) / 2,
                (getHeight() - size.height) / 2);
        component.revalidate();
        component.setVisible(true);
    }

    private void initHelpObjects() {
        
                 // handle the context sensitive help
             if  (GlobalValues.JavaCSHObject==null) {
                            GlobalValues.JavaCSHObject = new scalaExec.scalaLab.CSHObject();
                            GlobalValues.JavaCSHObject.setHelpSystem(GlobalValues.JavaHelpSetName);   // set the help system to Java JDK help
                }
            
            
            if  (GlobalValues.scalalabIDEHelpObject==null) {
                            GlobalValues.scalalabIDEHelpObject = new scalaExec.scalaLab.CSHObject();
                            GlobalValues.scalalabIDEHelpObject.setHelpSystem(GlobalValues.scalalabIDEHelpSetName);   
                }
    
    }

     private Vector     searchForClassWithRegularExpression(String regExp)  {
            Vector patternMatches = new Vector();
            Pattern classPattern = Pattern.compile(regExp);
            Hashtable  clTable= new Hashtable(); ///// SOS-Sterg scalaExec.Interpreter.GlobalValues.functionManager.getClassLoader().loadedClasses;
      Enumeration  iter = clTable.elements();
      while (iter.hasMoreElements() )
	 {   // consider all .class functions
	Object next = (Object)iter.nextElement();
        Class currentClass = (Class)next;
        String className = currentClass.getCanonicalName();
        
        Matcher   classPatternMatcher = classPattern.matcher(className);
        if (classPatternMatcher.find())   // class name fits with pattern
            patternMatches.add(className);
       }
      return patternMatches;
     }
            
        
     public static void detectPaths(String watchStr) {
         if (File.pathSeparatorChar==';')  {  // handle Windows file system naming
               int idxOfColon = watchStr.lastIndexOf(':'); 
               watchStr = watchStr.substring(idxOfColon-1, watchStr.length());
            }
            int sepIndex = watchStr.indexOf('!');
            if (sepIndex!=-1) {  
                
                String fullJarPath = watchStr.substring(0, sepIndex);
                System.out.println("fullJarPath = "+fullJarPath);
                String scalaLabJarName = fullJarPath.substring(fullJarPath.lastIndexOf(File.separatorChar)+1, fullJarPath.length() );
                if (scalaLabJarName.indexOf(File.separator)!=-1)
                    scalaLabJarName = scalaLabJarName.replaceAll(File.separator, "/");
                if (scalaLabJarName.contains("file:"))
                 scalaLabJarName = scalaLabJarName.replaceAll("file:", "");
                
                System.out.println("scalalabJarName = = "+scalaLabJarName);
                GlobalValues.jarFilePath = scalaLabJarName;
                
                GlobalValues.fullJarFilePath = fullJarPath;
                System.out.println("jarFilePath= = "+GlobalValues.jarFilePath);
                
                String scalalabLibPath = GlobalValues.jarFilePath;

                 int distIdx = scalalabLibPath.indexOf("dist");
                 if (distIdx !=-1 )   // run from within Netbeans
                       scalalabLibPath = scalalabLibPath.substring(0,  distIdx);
                 else {
                     int dotIndex = scalalabLibPath.indexOf(".");
                     int lastPos = dotIndex;
                     while (scalalabLibPath.charAt(lastPos)!='/' && scalalabLibPath.charAt(lastPos)!='\\'  && lastPos>0)
                             lastPos--;
                     scalalabLibPath = scalalabLibPath.substring(0, lastPos);
                 }
                 if (scalalabLibPath.length()>0)
                   scalalabLibPath = scalalabLibPath+File.separator+"lib"+File.separator;
                 else 
                  scalalabLibPath = "lib"+File.separator;
                     
                 GlobalValues.scalalabLibPath = scalalabLibPath;
                 System.out.println("GlobalValues.scalalabLibPath = "+GlobalValues.scalalabLibPath);
            }  // staring outside Netbeans
            
            else { // starting within Netbeans
                
                GlobalValues.jarFilePath = netbeansScalaLabArg;
                GlobalValues.fullJarFilePath = netbeansScalaLabArg.substring(0, netbeansScalaLabArg.lastIndexOf(File.separatorChar));
                System.out.println("scalalabJarName  = "+netbeansScalaLabArg);
                String libPath = netbeansScalaLabArg.substring(0, netbeansScalaLabArg.indexOf(File.separatorChar+"dist"));
                libPath = libPath.substring(0, libPath.lastIndexOf(File.separatorChar));
                
                String scalalabLibPath = libPath+File.separator+"lib"+File.separator;

        
                 GlobalValues.scalalabLibPath = scalalabLibPath;
                 System.out.println("GlobalValues.scalalabLibPath = "+GlobalValues.scalalabLibPath);
            }

     }
           
/**  Usage 
 *   scalaLab -jar  scalaLab.jar [<ScalaSciClassPath>] [pathToJarFile>]  
 *  the optional ScalaSciClassPath controls where to search for additional optional class files
 */
        public static void main(String[] args)
        {
    
            int argc;
            if (args!=null)
                argc = args.length;
            else argc = 0;

            if (argc > 0)
              netbeansScalaLabArg = args[0];
                
            GlobalValues.initScalaConsoleObj = new initScalaConsole();
         
          // the watchURL will serve to retrieve the name of the .jar file of the scalaLab system (i.e. "scalaLab.jar") 
       // the scalaLab's .jar file is used to load all the basic external classes and thus is very important.
       // When scalaLab is running within the Netbeans environment it is passed as the first program argument.          
          
         watchURL =  GlobalValues.initScalaConsoleObj.getClass().getResource("resources/systemsearch.png");
         String    watchStr = watchURL.toString();
         watchStr = decodeFileName(watchStr);
         
         detectPaths(watchStr);
            
         int scalaArgIndex = 0;  // index of "scala" command line argument for specifying console based ScalaLab execution  with the official Scala interpreter
         int sepIndex = watchStr.indexOf("build/classes");
         if (sepIndex != -1) // starting within Netbeans
           scalaArgIndex = 1;       

         if (args.length > scalaArgIndex)   {// command-line arguments exist
            if (args[scalaArgIndex].equalsIgnoreCase("scala"))  {
             GlobalValues.initScalaConsoleObj.scalaLabScalaConsole();
             }
         }
            else {
            GlobalValues.rt = Runtime.getRuntime();
            GlobalValues.memAvailable = GlobalValues.rt.freeMemory();
            
          
                    
  try {
            String vers = System.getProperty("java.version");
        if (vers.compareTo("1.5") < 0) {
            System.out.println("!!!scalaLab: Swing must be run with a 1.5 or higher version VM!!!");
            System.exit(1);
        }
            String currentWorkingDirectory = System.getenv("PWD");
            if (currentWorkingDirectory==null)
                currentWorkingDirectory = "c:\\"; 
            
           String userDir = System.getProperty("user.dir");
           currentWorkingDirectory = userDir; 
           if (File.separatorChar=='/')  { // detect OS type
        	    	GlobalValues.hostIsUnix = true;
             }
                        else {   // Windows host
                GlobalValues.hostIsUnix = false;
                if (currentWorkingDirectory == null)   // e.g. for Windows the current working directory is undefined
                currentWorkingDirectory = "C:\\";
            }
            if (GlobalValues.workingDir==null)
                         GlobalValues.workingDir = currentWorkingDirectory;
             
         
            String [] additionalToolboxes=null;
      
            if (argc>=2) {
                GlobalValues.ScalaSciClassPath = args[1];
            }
            
          
          GlobalValues.initGlobals();

    
          final scalaLab myGui = new scalaLab(GlobalValues.ScalaSciClassPath, additionalToolboxes);

           
            scalaLab.uiMainFrame = myGui;
            
     SwingUtilities.invokeLater(new Runnable() {
           public void run() {  // run in  */
              myGui.setLocation(xLocMainFrame, yLocMainFrame);
            
              myGui.setVisible(true);
          
              
//              ((scalaExec.gui.scalalabConsole)GlobalValues.userConsole).displayPrompt() ;

              
     
      }
     });
  }
      
       catch (StackOverflowError se) {
           JOptionPane.showMessageDialog(null, "Stack overflow error, try to use:   java -jar -Xss20m -Xms200m -Xmx1000m -jar scala;ab.jar ");
           se.printStackTrace();
       }
     catch (OutOfMemoryError oe){
           JOptionPane.showMessageDialog(null, "Out-of memory error, try to use:   java -jar -Xss20m -Xms200m -Xmx1000m -jar scala;ab.jar ");
           oe.printStackTrace();
              }
         }
 }
  


    public void windowActivated(WindowEvent e){}
    
    public void windowDeactivated(WindowEvent e){}
    
    public void windowClosed(WindowEvent e){ closeGUI(); }
   
    public void windowIconified(WindowEvent e){}

    public void windowDeiconified(WindowEvent e){}

    public void windowOpened(WindowEvent e){}



        public void windowClosing(WindowEvent e)
        {
        closeGUI();
        }
                
   }
   
  

